﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows;

namespace Faust.Andrew.MTG.Player.Converters
{
    /// <summary>
    /// Reorder the counters so that it's always Power then Toughness then everything else.
    /// </summary>
    public class CounterListConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            List<Shared.Counter> counters = new List<Faust.Andrew.MTG.Player.Shared.Counter>();
            
            if (value is IEnumerable<Shared.Counter>)
            {
                Shared.Counter power = null;
                Shared.Counter toughness = null;

                foreach (Shared.Counter counter in (value as IEnumerable<Shared.Counter>))
                {
                    if (counter.CounterType == Faust.Andrew.MTG.Player.Shared.CounterType.Power)
                    {
                        power = counter;
                    }
                    else if (counter.CounterType == Faust.Andrew.MTG.Player.Shared.CounterType.Toughness)
                    {
                        toughness = counter;
                    }
                    else
                    {
                        if (counter.Value != 0 && !String.IsNullOrEmpty(counter.StringValue))
                        {
                            counters.Add(counter);
                        }
                    }
                }

                if (toughness != null && toughness.Value != 0)
                {
                    counters.Insert(0, toughness);
                }

                if (power != null && power.Value != 0)
                {
                    counters.Insert(0, power);
                }

                //if (power != 0 || toughness != 0)
                //{
                //    Shared.Counter counter = new Faust.Andrew.MTG.Player.Shared.Counter();
                //    counter.CounterType = Faust.Andrew.MTG.Player.Shared.CounterType.Other;
                //    counter.Name = "Power / Toughness";
                //    counter.StringValue = String.Format("{0} / {1}", power, toughness);
                //    counters.Insert(0, counter);
                //}
            }

            return counters;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException("Converting back from CounterListControl to Enumerable not supported");
        }

        #endregion
    }
}
